from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from spit.models import Spit
from users.models import User
from spit.serializers import SpitSerializer
from django_redis import get_redis_connection
from rest_framework.response import Response
import logging
from spit.utils import transfer


# 创建日志生成器
logger = logging.getLogger('django')


# 获取吐槽详情
class SpitDetailViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitSerializer


# 获取吐槽详情
class SpitDetailView(APIView):
    # 登录用户才可以访问
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        redis_conn = get_redis_connection('default')
        try:
            spit = Spit.objects.get(id=pk)
            spit.visits += 1
            spit.save()
        except Exception as e:
            logger.error(e)
            return Response({'message': '访问数据库失败'})
        serializer = SpitSerializer(spit)
        result = serializer.data
        thumbup_user_id_set = redis_conn.smembers('thumbup_%s' % pk)
        user = request.user
        user_id = str(user.id).encode()
        if user_id not in thumbup_user_id_set:
            result['hasthumbup'] = False
        else:
            result['hasthumbup'] = True

        return Response(result)


# 吐槽评论
class SpitCommentView(APIView):
    # 登录用户才可以访问
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        query = Spit.objects.filter(parent_id=pk)
        serializer = SpitSerializer(query, many=True)
        results = serializer.data

        # 使用transfer判断用户以某种状态返回给前端
        data = transfer(results, request)
        return Response(data)


class SpitCreateView(APIView):

    #6.1 吐槽列表
    def get(self, request):

        spits = Spit.objects.filter(parent__isnull=True).order_by('-publishtime')
        serializer = SpitSerializer(spits, many=True)
        results = serializer.data

        # 调用transfer函数校验每个吐槽每个用户的状态
        results = transfer(results, request)

        return Response(results)

    #发表评论
    def post(self, request):

        data = request.data
        user = request.user
        content = data.get('content')
        if not content:
            message = '发布内容为空'
            return Response(message)

        parent = data.get('parent')
        # 发布吐槽
        if user.is_anonymous:
            if not parent:
                Spit.objects.create(content=content)
                return Response({'success': '匿名发布吐槽'})
            else:
                return None

        # 吐槽评论
        if parent:
            try:
                Spit.objects.create(userid=user.id, avatar=user.avatar,
                                    parent_id=parent, content=content)
                old_spit = Spit.objects.get(id=parent)
                old_spit.comment += 1
                old_spit.save()
            except Exception as e:
                logger.error(e)
                return Response({'message': '访问数据库失败'})
            return Response(content)


class SpitCollect(APIView):
    # 取消收藏或收藏
    def put(self, request, pk):
        try:
            spit = Spit.objects.get(id=pk)
            redis_conn = get_redis_connection('default')
            user_id_set = redis_conn.smembers('collected_%s' % pk)
        except Exception as e:
            logger.error(e)
            return Response({'message': '数据库访问失败'})

        user = request.user
        user_id = str(user.id).encode()

        if user_id in user_id_set:
            spit.collected = False
            spit.save()
            redis_conn.srem('collected_%s' % pk, user.id)
            data = {'message': '取消收藏', 'success': True}
            return Response(data)
        else:
            spit.collected = True
            spit.save()
            redis_conn.sadd('collected_%s' % pk, user.id)
            data = {'message': '收藏成功', 'success': True}

            return Response(data)

        # if spit.collected:
        #     # redis_conn.srem('collected_%s' % pk, user.id)
        #     spit.collected = False
        #     spit.save()
        #     data = {'message': '取消收藏', 'success': True}
        #     return Response(data)
        # else:
        #     # redis_conn.sadd('collected_%s' % pk, user.id)
        #     spit.collected = True
        #     spit.save()
        #     data = {'message': '收藏成功', 'success': True}
        #
        #     return Response(data)


class UpdateThumbUp(APIView):
    # 取消点赞成功或点赞
    def put(self, request, pk):

        try:
            spit = Spit.objects.get(id=pk)
            redis_conn = get_redis_connection('default')
            user_id_set = redis_conn.smembers('thumbup_%s' % pk)
        except Exception as e:
            logger.error(e)
            return Response({'message': '数据库访问失败'})

        user = request.user
        user_id = str(user.id).encode()
        if user_id in user_id_set:
            spit.thumbup -= 1
            spit.hasthumbup = False
            spit.save()
            redis_conn.srem('thumbup_%s' % pk, user.id)
            data = {'message': '取消点赞成功', 'success': True}
            return Response(data)
        else:
            redis_conn.sadd('thumbup_%s' % pk, user.id)
            spit.thumbup += 1
            spit.hasthumbup = True
            spit.save()
            data = {'message': '点赞成功', 'success': True}
            return Response(data)




